//
//  AddCommandViewController.m
//  McRemote
//
//  Created by Magic on 2/5/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AddCommandViewController.h"
#import "Event.h"

@interface AddCommandViewController () {

    NSArray *_keycodeTypeArray;
    NSArray *_keycodeArrayArray;
    NSArray *_iconNameArray;
    
    NSDictionary *_keycodeDictionary;
    
    NSInteger _currentType;
    NSInteger _keycodeIndex;
    
    
    BOOL _cmdAdded;
    BOOL _optAdded;
    BOOL _ctrlAdded;
    BOOL _shftAdded;
}

- (void)refreshIcon;
- (void)refreshPicker;
- (void)refreshShortcutDisplayText;
@property (readonly) NSString *currentKeycode;

@end

@implementation AddCommandViewController 

@synthesize commandPicker;
@synthesize commandLabel;
@synthesize delegate;
@synthesize newCommandIndex;
@synthesize flagsToolbar;
@synthesize flag,keyCode,title;
@synthesize titleField;
@synthesize toUpdate;
@synthesize customIconScrollView;
@synthesize icon;
@synthesize titleLabel, shortcutLabel, iconLabel;

- (void)awakeFromNib
{
    NSString *letter = NSLocalizedString(@"Letter", @"");
    NSString *number = NSLocalizedString(@"Number", @"");
    NSString *symbol = NSLocalizedString(@"Symbol", @"");
    NSString *function = NSLocalizedString(@"Function", @"");
    
    _iconNameArray = [NSArray arrayWithObjects:@"Customize1.png",@"Customize2.png",@"Customize3.png",@"Customize4.png",@"Customize5.png",@"Customize6.png",nil];
    
    _keycodeTypeArray = [NSArray arrayWithObjects:letter,number,symbol,function,nil];
    NSArray *keycodeLetterArray = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil];
    NSArray *keycodeNumberArray = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0",nil];
    NSArray *keycodeSymbolArray = [NSArray arrayWithObjects:@",",@".",@"/",@"\\",@"-",@"=",@";",@"'",@"[",@"]",@"`",nil];
    NSArray *keycodeFunctionArray = [NSArray arrayWithObjects:@"space",@"return",@"tab",@"delete",@"esc",@"→",@"←",@"↑",@"↓",@"F1",@"F2",@"F3",@"F4",@"F5",@"F6",@"F7",@"F8",@"F9",@"F10",@"F11",@"F12",nil];
    
    _keycodeArrayArray = [NSArray arrayWithObjects:keycodeLetterArray,keycodeNumberArray,keycodeSymbolArray,keycodeFunctionArray,nil];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Keycode" ofType:@"plist"];
    _keycodeDictionary = [NSDictionary dictionaryWithContentsOfFile:path];
    _keycodeDictionary = [_keycodeDictionary valueForKey:@"Keycode"];
    self.icon = [[NSString alloc] initWithFormat:@"Customize1.png"];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *titleText = NSLocalizedString(@"Title:", @"");
    NSString *shortcutText = NSLocalizedString(@"Shortcut:", @"");
    NSString *iconText = NSLocalizedString(@"Icon:", @"");
    self.titleLabel.text = titleText;
    self.shortcutLabel.text = shortcutText;
    self.iconLabel.text = iconText;
    
    self.view.backgroundColor = [UIColor colorWithRed:5.0f/255.0f green:5.0f/255.0f blue:5.0f/255.0f alpha:1.0f];
    self.commandPicker.frame = CGRectMake(0, 254, 320, 162);
    
    self.customIconScrollView.contentSize = CGSizeMake(540, 64);
    
    if (self.flag) {
        if (self.flag & kCGEventFlagMaskCommand) {
            _cmdAdded = YES;
        }
        if (self.flag & kCGEventFlagMaskShift) {
            _shftAdded = YES;
        }
        if (self.flag & kCGEventFlagMaskControl) {
            _ctrlAdded = YES;
        }
        if (self.flag & kCGEventFlagMaskAlternate) {
            _optAdded = YES;
        }
    }
    
    
    if (self.keyCode >= 0) {
        
        NSArray *keys = [_keycodeDictionary allKeysForObject:[NSNumber numberWithInt:self.keyCode]];
        NSString *key = [keys objectAtIndex:0];
        for (int i = 0; i < [_keycodeArrayArray count]; i++) {
            NSArray *array = [_keycodeArrayArray objectAtIndex:i];
            NSUInteger index = [array indexOfObject:key];
            if (index != NSNotFound) {
                _currentType = i;
                _keycodeIndex = index;
                break;
            }
        }
        
        [self refreshShortcutDisplayText];
        [self refreshPicker];
    }
    
    if (self.title) {
        self.titleField.text = self.title;
    }
    
    if (self.icon) {
        [self refreshIcon];
    }
    
    
/*    
    UIBarButtonItem *item0 = (UIBarButtonItem *)[self.flagsToolbar.items objectAtIndex:0];
    item0.target = self;
    item0.action = @selector(commandPressed:);
    
    UIBarButtonItem *item1 = (UIBarButtonItem *)[self.flagsToolbar.items objectAtIndex:1];
    item1.target = self;
    item1.action = @selector(optionPressed:);
    
    UIBarButtonItem *item2 = (UIBarButtonItem *)[self.flagsToolbar.items objectAtIndex:2];
    item2.target = self;
    item2.action = @selector(controlPressed:);
    
    UIBarButtonItem *item3 = (UIBarButtonItem *)[self.flagsToolbar.items objectAtIndex:3];
    item3.target = self;
    item3.action = @selector(shiftPressed:);*/
}



- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



#pragma mark - Private methods

- (NSString *)currentKeycode
{
    return [(NSArray *)[_keycodeArrayArray objectAtIndex:_currentType] objectAtIndex:_keycodeIndex];
}

- (void)refreshIcon
{
    NSUInteger index = [_iconNameArray indexOfObject:self.icon];
    customIconScrollView.contentOffset = CGPointMake(index*customIconScrollView.bounds.size.width, 0);
}

- (void)refreshPicker
{
    [self.commandPicker selectRow:_currentType inComponent:0 animated:NO];
    [self.commandPicker selectRow:_keycodeIndex inComponent:1 animated:NO];
}

- (void)refreshShortcutDisplayText
{
    NSString *shortcut = [[NSString alloc] initWithFormat:@""];
    
    if (_cmdAdded) {
        shortcut = [shortcut stringByAppendingFormat:@"Cmd + "];
    }
    if (_optAdded) {
        shortcut = [shortcut stringByAppendingFormat:@"Alt + "];
    }
    if (_ctrlAdded) {
        shortcut = [shortcut stringByAppendingFormat:@"Ctrl + "];
    }
    if (_shftAdded) {
        shortcut = [shortcut stringByAppendingFormat:@"Shift + "];
    }
    //if (self.keyCodeString) {
    shortcut = [shortcut stringByAppendingFormat:self.currentKeycode];
    //}
    
    self.commandLabel.text = shortcut;
}


#pragma mark - IBAction

- (void)commandPressed:(id)sender
{
    _cmdAdded = !_cmdAdded;

    [self refreshShortcutDisplayText]; 
}

- (void)optionPressed:(id)sender
{
    _optAdded = !_optAdded;

    [self refreshShortcutDisplayText];
}

- (void)controlPressed:(id)sender
{
    _ctrlAdded = !_ctrlAdded;
  
    [self refreshShortcutDisplayText];
}


- (void)shiftPressed:(id)sender
{
    _shftAdded = !_shftAdded;

    [self refreshShortcutDisplayText];
}

- (IBAction)doneItemClicked
{
    if ([self.titleField.text length] == 0) {
        NSString *ttl = NSLocalizedString(@"Couldn't Add Command", @"");
        NSString *msg = NSLocalizedString(@"Please fill in Title first", @"");
        NSString *ok = NSLocalizedString(@"OK", @"");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ttl message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:ok, nil];
        [alert show];
        
        return;
    }
    
    //set flag
    uint32_t newflag = 0;
    if (_cmdAdded) {
        newflag |= kCGEventFlagMaskCommand;
    }
    if (_shftAdded) {
        newflag |= kCGEventFlagMaskShift;
    }
    if (_ctrlAdded) {
        newflag |= kCGEventFlagMaskControl;
    }
    if (_optAdded) {
        newflag |= kCGEventFlagMaskAlternate;
    }
    self.flag = newflag;
    
    self.keyCode = [(NSNumber*)[_keycodeDictionary objectForKey:self.currentKeycode] intValue];
    
    self.title = self.titleField.text;
    
    if (self.delegate) {
        if (!self.toUpdate && [self.delegate respondsToSelector:@selector(addCommandAtIndex:fromViewController:)]) {
            [self.delegate addCommandAtIndex:self.newCommandIndex fromViewController:self];
        }
        else if (self.toUpdate && [self.delegate respondsToSelector:@selector(updateCommandAtIndex:fromViewController:)]) {
            [self.delegate updateCommandAtIndex:self.newCommandIndex fromViewController:self];
        }
    }
}

- (IBAction)cancelItemClicked
{
    if (self.delegate
        && [self.delegate respondsToSelector:@selector(cancelInAddCommandViewController:)]) {
        [self.delegate cancelInAddCommandViewController:self];
    }
}


#pragma mark - Picker callback

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return [_keycodeTypeArray count];
    }
    else
    {
        return [(NSArray *)[_keycodeArrayArray objectAtIndex:_currentType] count];        
        
    }

}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return [_keycodeTypeArray objectAtIndex:row];
    }
    else
    {
        return [(NSArray *)[_keycodeArrayArray objectAtIndex:_currentType] objectAtIndex:row];

        
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        _currentType = row;
        [self.commandPicker reloadComponent:1];
    }
    else
    {
        _keycodeIndex = row;
        [self refreshShortcutDisplayText];

    }    
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat offset = scrollView.contentOffset.x;
    NSLog(@"scroll to: %f",offset);
    
    int index = (int)(offset / scrollView.bounds.size.width);
    
    NSLog(@"scroll to index: %d",index);
    self.icon = [_iconNameArray objectAtIndex:index];
}


@end
